<?php
namespace Admin\Model;
use Think\Model\RelationModel;
class DatadictModel extends RelationModel{

	protected $tableName = 'datadict';

	/* 自动验证规则 */
	protected $_validate = array(
		array('id', 'number', '非法提交', self::MUST_VALIDATE, 'regex', self::MODEL_UPDATE),
		array('pid', 'number', '父级选择错误', self::MUST_VALIDATE , 'regex', self::MODEL_INSERT),
		array('category_id', 'number', '类型选择错误', self::MUST_VALIDATE , 'regex', self::MODEL_INSERT),
		array('title', '1,20', '标题字数介于0-40字', self::MUST_VALIDATE, 'length', self::MODEL_INSERT),
		array('value', '1,255', '值字数介于0-20字', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
		array('value', 'require', '值不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
		array('value', 'isunique', '值不能重复', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
		array('sort', 'number', '排序必须为数字', self::VALUE_VALIDATE , 'regex', self::MODEL_BOTH),
		array('status', array('0','1'), '状态错误', self::VALUE_VALIDATE , 'in', self::MODEL_BOTH),
	);

	// 自动完成规则
	protected $_auto = array (
		array('create_time','time',1,'function'), 
		array('update_time','time',3,'function'), 
		array('ext','json_encode',3,'function'),
		array('locked',0,1),
	);

	protected $_link = array(
		'datadictcate'=> array(
			'mapping_type'=> self::BELONGS_TO,
			'foreign_key'=>'category_id',
			'class_name'=>'datadictcate',
			'mapping_name'=>'datadictcate'
		)
	);

	protected function isunique(){
		$where = array();
		$where['category_id'] = array('EQ',I('category_id','','intval'));
		if (I('id','','intval')) {
			$where['id'] = array('NEQ',I('id','','intval'));
		}
		$values = M('Datadict') -> where($where) -> getField('value',true);
		if (in_array(I('value'), $values)) {
			return false;
		}
		return true;
	}
}